package com.api.pay.listener.consumer;

import com.api.pay.model.domain.ApiOrder;
import com.api.pay.service.ApiOrderService;
import com.api.pay.util.PayConstant;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;

import static com.api.pay.config.RabbitConfiguration.API_PAY_QUEUE_DLX;

//监听死信队列
@RabbitListener(queues = {API_PAY_QUEUE_DLX})
@Component
@Slf4j
public class OrderTimeOutHandler {
    @Autowired
    private ApiOrderService apiOrderService;

    /**
     * 订单超时处理
     *
     * @param apiOrder
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitHandler
    @Transactional(rollbackFor = Exception.class)
    public void receiveMessage(ApiOrder apiOrder, Message message, Channel channel) throws IOException {
        log.info("接收到消息:{}", message);
        //查询订单状态
        String status = apiOrderService.queryOrderStatus(apiOrder);
        //只有处于未支付或交易关闭状态时才能超时关闭订单
        if ("WAIT_BUYER_PAY".equals(status) || "TRADE_CLOSED".equals(status)) {
            QueryWrapper<ApiOrder> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("orderSn", apiOrder.getOrderSn());
            ApiOrder apiOrderFromDb = apiOrderService.getOne(queryWrapper);
            //当订单处于未支付状态,超时关闭
            if (apiOrderFromDb.getStatus().equals(PayConstant.TRADE_NO_PAY)) {
                UpdateWrapper<ApiOrder> updateWrapper = new UpdateWrapper<>();
                updateWrapper.set("status", PayConstant.TRADE_CLOSED);
                updateWrapper.eq("orderSn", apiOrderFromDb.getOrderSn());
                apiOrderService.update(updateWrapper);
            }
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
